# controller.py
import base64
from werkzeug.datastructures import FileStorage
import io
import os
import traceback
from flask import request, jsonify, current_app
# 根据内容识别文件类型
import imghdr
from app.services.ocr.service.upload_service import UploadService
from app.services.ocr.utils.utils import is_valid_base64, fix_base64_padding

upload_service = UploadService()


def system_upload_file(user_id):
    try:
        file = request.files.get('file')
        device_info = request.headers.get('User-Agent', '')
        ip_address = request.remote_addr or '127.0.0.1'

        result = upload_service.handle_upload(user_id, file, device_info, ip_address)

        return jsonify(result)
    except Exception as e:
        current_app.logger.error(f"上传处理异常: {str(e)}")
        current_app.logger.error(traceback.format_exc())
        return jsonify({"code": 0, "msg": "服务器内部错误"})


def system_upload_file_ai(user_id):
    try:
        file = request.files.get('file')
        device_info = request.headers.get('User-Agent', '')
        ip_address = request.remote_addr or '127.0.0.1'
        result = upload_service.handle_upload_ai(user_id, file, device_info, ip_address)
        return jsonify(result)
    except Exception as e:
        current_app.logger.error(f"上传处理异常: {str(e)}")
        current_app.logger.error(traceback.format_exc())
        return jsonify({"code": 0, "msg": "服务器内部错误"})


def system_upload_b64():
    try:
        data = request.get_json(force=True, silent=True) or {}
    except Exception:
        data = {}

    base64_str = data.get("base64") or request.values.get("base64")
    key = data.get("key") or request.values.get("key")

    if not base64_str or not key:
        return jsonify({"code": 400, "msg": "参数 base64 或 key 缺失"})

    if not key == 'qwertyuiop':
        return jsonify({"code": 0, "msg": "禁止使用该 key"})

    base64_str = fix_base64_padding(base64_str)

    if len(base64_str) < 20:
        return jsonify({"code": 400, "msg": "base64字符串太短"})

    if not is_valid_base64(base64_str):
        return jsonify({"code": 400, "msg": "base64编码不合法"})

    try:
        file_data = base64.b64decode(base64_str)
    except Exception as e:
        return jsonify({"code": 400, "msg": f"base64解码失败: {str(e)}"})

    file_type = imghdr.what(None, file_data)
    if not file_type or file_type not in {'jpeg', 'png', 'gif'}:
        return jsonify({"code": 0, "msg": "不支持的图片类型"})

    ext_map = {'jpeg': 'jpg', 'png': 'png', 'gif': 'gif'}
    file_ext = ext_map[file_type]
    filename = f'upload.{file_ext}'

    file_stream = io.BytesIO(file_data)
    file = FileStorage(stream=file_stream, filename=filename)

    result = upload_service.handle_upload(
        user_id=11,
        file=file,
        device_info=None,
        ip_address=None
    )

    return jsonify(result)
